import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/pages/user/broadcast/model/broadcast_item_data.dart';
import 'package:get/get.dart';

import 'state.dart';

class NoticeLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final state = NoticeState();

  fetchCate() async {
    var res = await Http.instance.post('/plugin/broadcast/api/cate');
    if (res.code == 1) {
      state.category = res.data;
      if (!state.isInit) {
        state.tabController =
            TabController(length: state.category.length, vsync: this);
        state.isInit = true;
      }
      state.loading = true;
    }
    fetchList();
    update(['category']);
  }

  fetchList() async {
    var res = await Http.instance.post('/plugin/broadcast/api/index', data: {
      "cate_id":
          state.category.isEmpty ? 0 : state.category[state.currentIndex]['id'],
      "page": state.pagination.currentPage,
    });
    state.uiStateController.setStatus(res);
    if (res.code == 1) {
      if (state.pagination.currentPage == 1) {
        state.list.clear();
      }
      state.pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => state.list.add(
          BroadcastItemData.fromJson(item),
        ),
      );
    }
    state.loading = false;
    update(['list']);
    state.refreshController.refreshCompleted();
    if (state.pagination.hasMore) {
      state.refreshController.loadComplete();
    } else {
      state.refreshController.loadNoData();
    }
  }

  onTabsClick(index) {
    state.currentIndex = index;
    state.loading = true;
    update(['list']);
    fetchList();
  }

  setRead(BroadcastItemData item) async {
    if (item.isRead == true) {
      return;
    }
    var res = await Http.instance.post('/plugin/broadcast/api/setRead', data: {
      "cate_id": state.category[state.currentIndex]['id'],
      "id": item.id,
    });
    if (res.code == 1) {
      item.isRead = true;
      update(['list']);
    }
  }
}
